﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.Events.Bus;
using Abp.UI;
using shenghua.Member.Members;
using shenghua.Member.XP.EventDatas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Member.XP
{
    public class XPManager: DomainService
    {
        public IEventBus EventBus { get; set; }
        private readonly IRepository<XPLog> _xpLogRepository;

        /// <summary>
        /// 这里只能使用IRepository，而不能使用memberManager。这里的member实体类实际上充当了会员与积分的映射类的身份
        /// </summary>
        private readonly IRepository<Member.Members.Member, long> _memberRepository;

        public XPManager(
            IRepository<XPLog> xpLogRepository,
            IRepository<Member.Members.Member, long> memberRepository
            )
        {
            _xpLogRepository = xpLogRepository;
            _memberRepository = memberRepository;
            EventBus = NullEventBus.Instance;
        }

        public async Task ChangeXP(long memberId, int xpValue, string description, bool shouldChangeTotal = false)
        {
            var member = await _memberRepository.FirstOrDefaultAsync(memberId);
            if(member == null)
            {
                throw new UserFriendlyException("会员不存在，无法修改积分");
            }

            member.XPValue += xpValue;
            if(member.XPValue < 0)
            {
                throw new UserFriendlyException("积分不能小于零");
            }

            if(shouldChangeTotal)
            {
                member.TotalXPValue += xpValue;

                EventBus.Trigger(new AfterChangeTotalXPValueEventData
                {
                    MemberId = memberId,
                    ChangedXPValue = xpValue,
                    TotalXPValue = member.TotalXPValue
                });
            }

            XPLog log = new XPLog
            {
                MemberId = member.Id,
                ChangeValue = xpValue,
                Description = description
            };
            await _xpLogRepository.InsertAsync(log);
        }

        public async Task<List<XPLog>> GetAll(long memberId)
        {
            return await _xpLogRepository.GetAllListAsync(r => r.MemberId == memberId);
        }
    }
}
